package com.cwvs.helper;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.cwvs.utils.AppUtil;
import com.cwvs.utils.ObjectId;

/**
 * 文件上传helper
 */
@Component
public class FileUploadHelper {

	@Resource
	private FileRootHelper fileRootHelper;
	private static Logger logger = Logger.getLogger(FileUploadHelper.class);
	@Resource
	private ImageHandleHelper imageHandleHelper;

	/**
	 * 根据不同类型生成不同的目录名称
	 * 
	 * @param typeVal
	 * @return
	 */
	private String genrateFileFloderName(int typeVal) {
		String floderName = "";
		switch (typeVal) {
		case 1:
			// 店铺路径
			floderName = "store";
			break;
		case 2:
			// 头像路径
			floderName = "header";
			break;
		case 3:
			// 需求路径
			floderName = "need";
			break;
		default:
			// 常规默认路径
			floderName = "notype";
			break;
		}
		return floderName;
	}

	// private String genrateImageFileFloder(String name, int typeVal) {
	// String fileFloder = "";
	// String type = genrateFileFloderName(typeVal);
	// if (null != name && type.length() > 0) {
	// fileFloder = handleFilePath(fileRootHelper.getImageFileRoot())
	// + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + type + "/"
	// + genrateHashFileFloder(name) + "/";
	// }
	// return fileFloder;
	// }

	/**
	 * 生成头像图片文件夹名称
	 * 
	 * @param name
	 * @param typeVal
	 * @return
	 */
	private String[] headImageFileFloder(int date) {
		String[] fileFloder = new String[] { "same", "bbig", "big", "medium",
				"normal", "small" };
		String[] path = new String[6];
		if (date < 1000000) {
			date = AppUtil.getIntNow();
		}
		String uuid = String.valueOf(date);
		String nuid = uuid.substring(uuid.length() - 6, uuid.length());
		// String type = genrateFileFloderName(typeVal);
		for (int i = 0; i < fileFloder.length; i++) {
			path[i] = handleFilePath(fileRootHelper.getImageFileRoot())
					+ genrateFileFloderName(2) + "/" + nuid.substring(0, 2)
					+ "/" + nuid.substring(2, 4) + "/" + nuid.substring(4, 6)
					+ "/" + fileFloder[i] + "/";
		}
		return path;
	}

	/**
	 * 生成图片文件夹名称
	 * 
	 * @param name
	 * @param typeVal
	 * @return
	 */
	private String[] imageFileFloder(int date, int type) {
		String[] fileFloder = new String[] { "temp", "normal" };
		String[] path = new String[2];
		if (date < 1000000) {
			date = AppUtil.getIntNow();
		}
		String uuid = String.valueOf(date);
		String nuid = uuid.substring(uuid.length() - 6, uuid.length());
		for (int i = 0; i < fileFloder.length; i++) {
			path[i] = handleFilePath(fileRootHelper.getImageFileRoot())
					+ genrateFileFloderName(type) + "/" + nuid.substring(0, 2)
					+ "/" + nuid.substring(2, 4) + "/" + nuid.substring(4, 6)
					+ "/" + fileFloder[i] + "/";
		}
		return path;
	}

	// /**
	// * 生成压缩文件的保存目录位置
	// *
	// * @param name
	// * @return
	// */
	// private String genrateCompressionFileFloder(String name) {
	// String fileFloder = "";
	// if (null != name && name.trim().length() > 0) {
	// fileFloder = handleFilePath(fileRootHelper.getCompressionFileRoot())
	// + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" +
	// genrateHashFileFloder(name)
	// + "/" + name + "/";
	// }
	// return fileFloder;
	// }

	/**
	 * 根据名称的hashcode生成文件夹名称
	 * 
	 * @param name
	 * @return
	 */
	private String genrateHashFileFloder(String name) {
		String code = Math.abs(name.hashCode() % 1000) + "";
		switch (code.length()) {
		case 1:
			code = "00" + code;
			break;
		case 2:
			code = "0" + code;
			break;
		}
		return code;
	}

	/**
	 * 处理文件位置
	 * 
	 * @param fileName
	 * @return
	 */
	private String handleFilePath(String fileName) {
		if (null != fileName) {
			fileName = fileName.replace("\\", "/");
			if (!fileName.endsWith("/")) {
				fileName += "/";
			}
		}
		return fileName;
	}

	/**
	 * 批量处理文件位置
	 * 
	 * @param fileName
	 * @return
	 */
	private String[] handleFilePath(String[] fileName) {
		if (fileName.length != 0) {
			for (int i = 0; i < fileName.length; i++) {
				fileName[i] = fileName[i].replace("\\", "/");
				if (!fileName[i].endsWith("/")) {
					fileName[i] += "/";
				}
			}
		}
		return fileName;
	}

	// /**
	// * 执行文件的写入
	// *
	// * @param commonsMultipartFile
	// * @param typeVal
	// * @param fileType 1图片文件2压缩文件
	// * @return
	// * @throws Exception
	// */
	// private String writeFile(CommonsMultipartFile commonsMultipartFile,
	// Integer typeVal, int fileType) throws Exception {
	// String path = "";
	// if (null != commonsMultipartFile && !commonsMultipartFile.isEmpty()) {
	// String uuid = UUID.randomUUID().toString();
	// if (fileType == 1 || fileType == 3) { // 图片文件
	// String name = uuid
	// + commonsMultipartFile.getOriginalFilename().substring(
	// commonsMultipartFile.getOriginalFilename().lastIndexOf(
	// "."));
	// String floderName = handleFilePath(genrateImageFileFloder(name,
	// typeVal));
	// File dir = new File(floderName);
	// if (!dir.exists()) {
	// dir.mkdirs();
	// }
	// DataOutputStream dataOutputStream = new DataOutputStream(new
	// FileOutputStream(floderName + name));
	// InputStream is = commonsMultipartFile.getInputStream();
	// byte[] buffer = new byte[1024];
	// while (is.read(buffer) != -1) {
	// dataOutputStream.write(buffer, 0, buffer.length);
	// }
	// dataOutputStream.flush();
	// is.close();
	// dataOutputStream.close();
	// String fileAbsolutePath = floderName + name;
	//
	// if (fileType == 1) {
	// // 添加水印
	// // imageHandleHelper.addImageWaterMark(fileAbsolutePath);
	// // 生成对应的大图、中图、小图
	// // imageHandleHelper.genrateThumbnail(dir, uuid, fileAbsolutePath);
	// } else if (fileType == 3) {
	//
	// }
	// String paths =
	// fileAbsolutePath.substring(handleFilePath(fileRootHelper.getImageFileRoot()).length());
	// if (StringUtils.isNotBlank(paths)) {
	// MagickImage image = new MagickImage(new ImageInfo(fileAbsolutePath));
	// Dimension dimension = image.getDimension();
	// int width = dimension.width;
	// int height = dimension.height;
	// String name1 = uuid
	// + "_row"
	// + commonsMultipartFile.getOriginalFilename().substring(
	// commonsMultipartFile.getOriginalFilename().lastIndexOf(
	// "."));
	// String fileAbsolutePaths = floderName + name1;
	// path =
	// fileAbsolutePaths.substring(handleFilePath(fileRootHelper.getImageFileRoot()).length());
	// if (width > 800 && height > 600) {
	// ImageInfo info = null;
	// MagickImage image1 = null;
	// MagickImage scaled = null;
	//
	// String target = new File(dir, name1).getAbsolutePath();
	// try {
	// info = new ImageInfo(fileAbsolutePath);
	// image1 = new MagickImage(info);
	//
	// scaled = image1.scaleImage(800, 600);
	// scaled.setFileName(target);
	// scaled.writeImage(info);
	// } catch (MagickException e) {
	// e.printStackTrace();
	// throw new Exception(e);
	// } finally {
	// if (null != scaled) {
	// scaled.destroyImages();
	// }
	// }
	// return path;
	// } else {
	// DataOutputStream dataOutputStream1 = new DataOutputStream(new
	// FileOutputStream(floderName
	// + name1));
	// InputStream iss = commonsMultipartFile.getInputStream();
	// byte[] buffers = new byte[1024];
	// while (iss.read(buffers) != -1) {
	// dataOutputStream1.write(buffers, 0, buffers.length);
	// }
	// dataOutputStream1.flush();
	// iss.close();
	// dataOutputStream1.close();
	// return path;
	// }
	// }
	// } else if (fileType == 2) { // 压缩文件
	// String floderName = handleFilePath(genrateCompressionFileFloder(uuid));
	// File dir = new File(floderName);
	// if (!dir.exists()) {
	// dir.mkdirs();
	// }
	//
	// String compressionName = commonsMultipartFile.getOriginalFilename();
	// DataOutputStream dataOutputStream = new DataOutputStream(new
	// FileOutputStream(floderName
	// + compressionName));
	// InputStream is = commonsMultipartFile.getInputStream();
	//
	// int len = -1;
	// byte[] buffer = new byte[1024];
	// while ((len = is.read(buffer)) != -1) {
	// dataOutputStream.write(buffer, 0, len);
	// }
	// dataOutputStream.flush();
	// is.close();
	// dataOutputStream.close();
	//
	// path = floderName + compressionName;
	// } else {
	// throw new Exception("要保存的文件类型错误！");
	// }
	// }
	// return path;
	// }

	// /**
	// * 单个图片文件上传
	// *
	// * @param request
	// * @param typeVal
	// *
	// 1代表"品牌",2代表"商品",3代表"店铺",4代表"商家",5代表"退款",6代表"举报",7代表"代理商",8代表"首页特性图片",9代表"首页专区",10代表"类目",11代表"首页广告",12代表"首页销售专场",
	// * 13代表"首页品牌专场",14代表"平台调用"
	// * @return
	// * @throws Exception
	// */
	// public String fileUpload(HttpServletRequest request, int typeVal) throws
	// Exception {
	// String path = "";
	// if (request instanceof MultipartHttpServletRequest) {
	// path = writeFile((CommonsMultipartFile) (((MultipartHttpServletRequest)
	// request).getFile("file")), typeVal,
	// 1);
	// }
	// return path;
	// }

	// /**
	// * 单个图片文件上传
	// *
	// * @param request
	// * @param fileAttrName 保存文件路径的字段对应的属性的名字
	// * @param typeVal
	// 1代表"品牌",2代表"商品",3代表"店铺",4代表"商家",5代表"退款",6代表"举报",7代表"代理商",8代表"首页特性图片",9代表"首页专区",10代表"类目"
	// * @return
	// * @throws Exception
	// */
	// public String fileUpload(HttpServletRequest request, String fileAttrName,
	// int typeVal) throws Exception {
	// String path = "";
	// if (request instanceof MultipartHttpServletRequest) {
	// path = writeFile((CommonsMultipartFile) (((MultipartHttpServletRequest)
	// request).getFile(fileAttrName)),
	// typeVal, 1);
	// }
	// return path;
	// }

	/**
	 * 头像图片文件上传
	 * 
	 * @param request
	 * @param fileAttrName
	 *            保存文件路径的字段对应的属性的名字
	 * @return
	 * @throws Exception
	 */
	public String[] headImagefileUpload(String fileAttrName, int userId, int x,
			int y, int w, int h,boolean iswater,boolean cut) throws Exception {
		String[] path = new String[5];
		path = headImagewriteFile(fileAttrName, userId, x, y, w, h,iswater,cut);
		return path;
	}

	// /**
	// * 单个图片文件上传(没有任何处理，仅仅上传源文件)
	// *
	// * @param request
	// * @param fileAttrName 保存文件路径的字段对应的属性的名字
	// * @param typeVal
	// *
	// 1代表"品牌",2代表"商品",3代表"店铺",4代表"商家",5代表"退款",6代表"举报",7代表"代理商",8代表"首页特性图片",9代表"首页专区",10代表"类目",11代表"首页广告",12代表"首页销售专场",
	// * 13代表"首页品牌专场"
	// * @return
	// * @throws Exception
	// */
	// public String imageFileUploadWithNoOtherHandle(HttpServletRequest
	// request, String fileAttrName, int typeVal)
	// throws Exception {
	// String path = "";
	// if (request instanceof MultipartHttpServletRequest) {
	// path = writeFile((CommonsMultipartFile) (((MultipartHttpServletRequest)
	// request).getFile(fileAttrName)),
	// typeVal, 3);
	// }
	// return path;
	// }

	// /**
	// * 压缩文件的上传
	// *
	// * @param request
	// * @param fileAttrName
	// * @return
	// * @throws Exception
	// */
	// public String compressionFileUpload(HttpServletRequest request, String
	// fileAttrName) throws Exception {
	// String path = "";
	//
	// if (null == fileAttrName || fileAttrName.trim().length() == 0) {
	// fileAttrName = "file";
	// }
	//
	// if (request instanceof MultipartHttpServletRequest) {
	// path = writeFile((CommonsMultipartFile) (((MultipartHttpServletRequest)
	// request).getFile(fileAttrName)),
	// null, 2);
	// }
	//
	// return path;
	// }

	// /**
	// * 图片文件的批量处理
	// *
	// * @param request
	// * @param typeVal
	// *
	// 1代表"品牌",2代表"商品",3代表"店铺",4代表"商家",5代表"退款",6代表"举报",7代表"代理商",8代表"首页特性图片",9代表"首页专区",10代表"类目",11代表"首页广告",12代表"首页销售专场",
	// * 13代表"首页品牌专场"
	// * @return 返回map类型,key为在form表单中定义的
	// * @throws Exception
	// */
	// public Map<String, String> fileUploadBatch(HttpServletRequest request,
	// int typeVal) throws Exception {
	// Map<String, String> map = new HashMap<String, String>();
	// if (request instanceof MultipartHttpServletRequest) {
	// MultipartHttpServletRequest multipartHttpServletRequest =
	// (MultipartHttpServletRequest) request;
	// Iterator<String> it = multipartHttpServletRequest.getFileNames();
	// while (it.hasNext()) {
	// String key = it.next();
	// map.put(key, writeFile((CommonsMultipartFile)
	// multipartHttpServletRequest.getFile(key), typeVal, 1));
	// }
	// }
	// return map;
	// }

	/**
	 * 写图片文件到指定的目录,适用于文件已经在服务器上,键保存的是不包含绝对路径的文件名,值保存的是除去系统设置的资源位置后的路径
	 * 
	 * @param fileNames
	 *            文件绝对路径组成的数组
	 * @param typeVal
	 *            类型
	 * @param substr
	 *            是否需要截取
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> writeImageFiles(String[] fileNames, int typeVal,
			boolean substr) throws Exception {
		Map<String, String> ret = new HashMap<String, String>();
		if (null != fileNames && fileNames.length > 0) {
			String fileRoot = handleFilePath(fileRootHelper.getImageFileRoot());
			String floder = genrateFileFloderName(typeVal);
			String floderName = handleFilePath(handleFilePath(fileRoot)
					+ floder)
					+ new SimpleDateFormat("yyyyMMdd").format(new Date());
			for (int i = 0; i < fileNames.length; i++) {
				File file = new File(fileNames[i]);
				if (null != file && file.exists() && file.isFile()) {
					String uuid = UUID.randomUUID().toString();
					String fileName = floderName + genrateHashFileFloder(uuid);
					if (file.getName().indexOf(".") != -1) {
						fileName = floderName
								+ genrateHashFileFloder(uuid)
								+ file.getName().substring(
										file.getName().lastIndexOf("."));
					}
					File targetFile = new File(fileName);
					if (targetFile.exists()) {
						targetFile.delete();
					}
					targetFile.createNewFile();
					OutputStream out = new DataOutputStream(
							new FileOutputStream(targetFile));
					InputStream in = new DataInputStream(new FileInputStream(
							file));
					int len = -1;
					byte[] bs = new byte[1024];
					while ((len = in.read(bs)) != -1) {
						out.write(bs, 0, len);
					}
					out.flush();
					in.close();
					out.close();
					if (substr) {
						ret.put(file.getName(),
								fileName.substring(fileRoot.length()));
					} else {

					}
				}
			}
		}
		return ret;
	}

	/**
	 * 头像上传
	 * 
	 * @param commonsMultipartFile
	 * @param typeVal
	 * @param fileType
	 * @return
	 * @throws Exception
	 */
	private String[] headImagewriteFile(String oldImageUrl, int date, int x,
			int y, int w, int h,boolean iswater,boolean cut) throws Exception {
		String[] path = new String[6];
		int[] widths = new int[] { 1, 120, 91, 36, 30, 19 };
		int[] heights = new int[] { 1, 120, 91, 36, 30, 19 };
		String objectId = ObjectId.getObjectId();
		String name = objectId + ".gif";
		String[] floderName = handleFilePath(headImageFileFloder(date));
		for (int i = 0; i < floderName.length; i++) {

			File dir = new File(floderName[i]);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			String fileAbsolutePath = floderName[i] + name;
			String file = floderName[0] + name;
			if (i == 0) {
				try {
					Image img;
					ImageFilter cropFilter;
					// 读取源图像
					URL url = new URL(oldImageUrl);
					InputStream is = url.openConnection().getInputStream();
					BufferedImage bi = ImageIO.read(is);
					int srcWidth = bi.getWidth(); // 源图宽度
					int srcHeight = bi.getHeight(); // 源图高度
					if (srcWidth >= w && srcHeight >= h) {
						Image image = bi.getScaledInstance(srcWidth, srcHeight,
								Image.SCALE_DEFAULT);
						// 四个参数分别为图像起点坐标和宽高
						// 即: CropImageFilter(int x,int y,int width,int height)
						cropFilter = new CropImageFilter(x, y, w, h);
						img = Toolkit.getDefaultToolkit().createImage(
								new FilteredImageSource(image.getSource(),
										cropFilter));
						BufferedImage tag = new BufferedImage(w, h,
								BufferedImage.TYPE_INT_RGB);
						Graphics g = tag.getGraphics();
						g.drawImage(img, 0, 0, null); // 绘制缩小后的图
						g.dispose();

						// 输出为文件
						ImageIO.write(tag, "GIF", new File(file));

						// 清空内存
						tag.flush();

						// close stream
						if (is != null) {
							is.close();
						}
					}
				} catch (Exception e) {
					logger.error("图片截取出现异常", e);
				}
			} else {
				fileAbsolutePath = imageHandleHelper.headImageThumbnail(dir,
						floderName[0], file, objectId, widths[i], heights[i],iswater,cut);
			}
			path[i] = fileAbsolutePath.substring(handleFilePath(
					fileRootHelper.getImageFileRoot()).length());
		}
		return path;
	}

	// /**
	// * 上传非图片文件
	// *
	// * @param request
	// * @param fileAttrName
	// * @return
	// * @throws Exception
	// */
	// public String fileUploadNonImageFile(HttpServletRequest request, String
	// fileAttrName) throws Exception {
	// String path = "";
	// if (request instanceof MultipartHttpServletRequest) {
	// path = writeFile((CommonsMultipartFile) (((MultipartHttpServletRequest)
	// request).getFile(fileAttrName)),
	// null, 2, null, null);
	// }
	// return path;
	// }

	// /**
	// * 执行文件的写入
	// *
	// * @param commonsMultipartFile
	// * @param typeVal
	// * @param fileType 1图片文件2压缩文件
	// * @param needAddWaterMark 是否添加水印，默认不添加
	// * @param needThumbnail 是否生成压缩图片，默认不生成
	// * @return
	// * @throws Exception
	// */
	// private String writeFile(CommonsMultipartFile commonsMultipartFile,
	// Integer typeVal, int fileType,
	// Boolean needAddWaterMark, Boolean needThumbnail) throws Exception {
	// String path = "";
	// if (null != commonsMultipartFile && !commonsMultipartFile.isEmpty()) {
	// String uuid = UUID.randomUUID().toString();
	// if (fileType == 1 || fileType == 3) { // 图片文件
	// String name = uuid
	// + commonsMultipartFile.getOriginalFilename().substring(
	// commonsMultipartFile.getOriginalFilename().lastIndexOf(
	// "."));
	// String floderName =
	// fileRootHelper.handleFolderPath(genrateImageFileFloder(name, typeVal));
	// File dir = new File(floderName);
	// if (!dir.exists()) {
	// dir.mkdirs();
	// }
	// DataOutputStream dataOutputStream = new DataOutputStream(new
	// FileOutputStream(floderName + name));
	// InputStream is = commonsMultipartFile.getInputStream();
	// byte[] buffer = new byte[1024];
	// int len = -1;
	// while ((len = is.read(buffer)) != -1) {
	// dataOutputStream.write(buffer, 0, len);
	// }
	// dataOutputStream.flush();
	// is.close();
	// dataOutputStream.close();
	// String fileAbsolutePath = floderName + name;
	//
	// if (fileType == 1) {
	// // 默认不添加水印
	// if (null == needAddWaterMark) {
	// needAddWaterMark = false;
	// }
	// // 默认不生成压缩图
	// if (null == needThumbnail) {
	// needThumbnail = false;
	// }
	// // 生成对应的大图、中图、小图
	// if (needThumbnail) {
	// imageHandleHelper.genrateThumbnail(dir, uuid, fileAbsolutePath,
	// needAddWaterMark);
	// }
	// // 添加水印
	// if (needAddWaterMark) {
	// imageHandleHelper.addImageWaterMark(fileAbsolutePath);
	// }
	// } else if (fileType == 3) {
	//
	// }
	// path =
	// fileAbsolutePath.substring(fileRootHelper.handleFolderPath(fileRootHelper.getImageFileRoot()).length());
	// } else if (fileType == 2) { // 压缩文件或其他非图片文件
	// String floderName =
	// fileRootHelper.handleFolderPath(fileRootHelper.genrateUploadAndDownloadFileFloder(
	// uuid,
	// 5,
	// null));
	// String compressionName = commonsMultipartFile.getOriginalFilename();
	// DataOutputStream dataOutputStream = new DataOutputStream(new
	// FileOutputStream(floderName
	// + compressionName));
	// InputStream is = commonsMultipartFile.getInputStream();
	// int len = -1;
	// byte[] buffer = new byte[1024];
	// while ((len = is.read(buffer)) != -1) {
	// dataOutputStream.write(buffer, 0, len);
	// }
	// dataOutputStream.flush();
	// is.close();
	// dataOutputStream.close();
	// path = floderName + compressionName;
	// } else {
	// throw new Exception("要保存的文件类型错误！");
	// }
	// }
	// return path;
	// }
	/**
	 * 头像图片文件上传
	 * 
	 * @param request
	 * @param fileAttrName
	 *            保存文件路径的字段对应的属性的名字
	 * @return
	 * @throws Exception
	 */
	public String[] headImagefileUpload(HttpServletRequest request,
			String fileAttrName, int date,boolean iswater,boolean cut) throws Exception {
		String[] path = new String[6];
		if (request instanceof MultipartHttpServletRequest) {
			path = headImagewriteFile(
					(CommonsMultipartFile) (((MultipartHttpServletRequest) request)
							.getFile(fileAttrName)), date,iswater,cut);
		}
		return path;
	}

	/**
	 * 单图片处理
	 */
	public String imageFileUpload(HttpServletRequest request,
			String fileAttrName, int date, int type, int width, int height,boolean iswater,boolean cut)
			throws Exception {
		String path = null;
		if (request instanceof MultipartHttpServletRequest) {
			path = imagewriteFile(
					(CommonsMultipartFile) (((MultipartHttpServletRequest) request)
							.getFile(fileAttrName)), date, type, width, height,iswater,cut);
		}
		return path;

	}

	/**
	 * 头像上传
	 * 
	 * @param commonsMultipartFile
	 * @param typeVal
	 * @param fileType
	 * @return
	 * @throws Exception
	 */
	private String[] headImagewriteFile(
			CommonsMultipartFile commonsMultipartFile, int date,boolean iswater,boolean cut)
			throws Exception {
		String[] path = new String[6];
		int[] widths = new int[] { 1, 120, 90, 36, 30, 19 };
		int[] heights = new int[] { 1, 120, 90, 36, 30, 19 };
		if (null != commonsMultipartFile && !commonsMultipartFile.isEmpty()) {
			String uuid = ObjectId.getObjectId();
			String name = uuid
					+ commonsMultipartFile.getOriginalFilename().substring(
							commonsMultipartFile.getOriginalFilename()
									.lastIndexOf("."));
			String[] floderName = handleFilePath(headImageFileFloder(date));
			for (int i = 0; i < floderName.length; i++) {
				File dir = new File(floderName[i]);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				String fileAbsolutePath = floderName[i] + name;
				String file = floderName[0] + name;
				if (i == 0) {
					DataOutputStream dataOutputStream = new DataOutputStream(
							new FileOutputStream(floderName[i] + name));
					InputStream is = commonsMultipartFile.getInputStream();
					byte[] buffer = new byte[1024];
					while (is.read(buffer) != -1) {
						dataOutputStream.write(buffer, 0, buffer.length);
					}
					dataOutputStream.flush();
					is.close();
					dataOutputStream.close();
				} else {
					fileAbsolutePath = imageHandleHelper.headImageThumbnail(
							dir, floderName[0], file, uuid, widths[i],
							heights[i],iswater,cut);
				}
				path[i] = fileAbsolutePath.substring(handleFilePath(
						fileRootHelper.getImageFileRoot()).length());
			}
		}
		// System.out.println(path.length);
		return path;
	}

	/**
	 * 单图片上传
	 * 
	 * @param commonsMultipartFile
	 * @param typeVal
	 * @param fileType
	 * @return
	 * @throws Exception
	 */
	private String imagewriteFile(CommonsMultipartFile commonsMultipartFile,
			int date, int type, int width, int height,boolean iswater,boolean cut) throws Exception {
		String[] path = new String[2];
		int[] widths = new int[] { 1, width };
		int[] heights = new int[] { 1, height };
		if (null != commonsMultipartFile && !commonsMultipartFile.isEmpty()) {
			String uuid = ObjectId.getObjectId();
			String name = uuid
					+ commonsMultipartFile.getOriginalFilename().substring(
							commonsMultipartFile.getOriginalFilename()
									.lastIndexOf("."));
			String[] floderName = handleFilePath(imageFileFloder(date, type));
			for (int i = 0; i < floderName.length; i++) {
				File dir = new File(floderName[i]);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				String fileAbsolutePath = floderName[i] + name;
				String file = floderName[0] + name;
				if (i == 0) {
					DataOutputStream dataOutputStream = new DataOutputStream(
							new FileOutputStream(floderName[i] + name));
					InputStream is = commonsMultipartFile.getInputStream();
					byte[] buffer = new byte[1024];
					while (is.read(buffer) != -1) {
						dataOutputStream.write(buffer, 0, buffer.length);
					}
					dataOutputStream.flush();
					is.close();
					dataOutputStream.close();
				} else {
					fileAbsolutePath = imageHandleHelper.headImageThumbnail(
							dir, floderName[0], file, uuid, widths[i],
							heights[i],iswater,cut);
				}
				path[i] = fileAbsolutePath.substring(handleFilePath(
						fileRootHelper.getImageFileRoot()).length());
			}
		}
		// System.out.println(path.length);
		return path[1];
	}
}
